<script setup>
import { ref, onMounted } from 'vue'
import useUserInfoStore from '@/stores/userInfo.js'
import { useTokenStore } from '@/stores/token.js'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { devicePageQueryService, deviceInfoUpdateService, deviceDeleteService, deviceInfoGetService, deviceRegisterService, deviceNameGetService } from '@/api/device.js'
import { districtTreeQueryService, districtInfoGetService, districtGetFullNameService } from '@/api/district.js'
import { parseDistrictTree, districtTypeList, getDistrictTypeName, getDistrictFullName } from '@/utils/district.js';
import {getDeviceTypeName, deviceTypeList, getDeviceStatusName, deviceStatusList} from '@/utils/device.js'
import DeviceDetail from './DeviceDetail.vue'


const uploadRef = ref()
const userInfoStore = useUserInfoStore()
const tokenStore = useTokenStore()
const router = useRouter()

// 列表的物品总数
const itemsTotal = ref(1)

// 设备分页查询的表单结构
const devicePageQueryData = ref({
    page: 1,
    pageSize: 5,
    id: null,
    name: null,
    type: null,
    status: null,
    parentId: null,
    districtId: null,
    posId: null,
    macAddr: null
})

const devices = ref([])

const parentDeviceName = ref('')

const getParentName = async (id) => {
    if(id === ''){
        parentDeviceName.value = ''
        return
    }
    if(id !== null){
        let res = await deviceNameGetService(id)
        parentDeviceName.value = res.data
    }

}

//定义表单校验规则
const rules = {
    name: [
        { required: true, message: '设备名不能为空', trigger: 'blur' },
    ],
    macAddr: [
        { required: true, message: '设备MAC地址不能为空', trigger: 'blur' },
    ],
    districtId: [
        { required: true, message: '所属片区不能为空', trigger: 'blur' },
    ],
    type: [
        { required: true, message: '设备类型不能为空', trigger: 'blur' },
    ]
}

// 区域数据
const districts = ref([])
const parsedDistrictTreeData = ref([])

// 获取区域数据
const getDistrictTree = async () => {
    let result = await districtTreeQueryService(-1) // 假设根节点ID为0
    let tree = result.data
    parsedDistrictTreeData.value = parseDistrictTree(tree)
}

// 在组件挂载时获取区域数据
onMounted(() => {
    getDevices()
})

// 分页查询获取设备列表
const getDevices = async () => {
    let result = await devicePageQueryService(devicePageQueryData.value)
    devices.value = result.records
    itemsTotal.value = result.total
    for(let i = 0;i < devices.value.length; i++){
        devices.value[i].typeName = getDeviceTypeName(devices.value[i])
        devices.value[i].statusName = getDeviceStatusName(devices.value[i])
    }
}
// 页面加载时获取一次所有设备
getDevices()
getDistrictTree()

// 分页大小改变时重新分页查询
const handleSizeChange = (val) => {
    devicePageQueryData.value.pageSize = val
    getDevices()
}
// 分页页码改变时重新分页查询
const handleCurrentChange = (val) => {
    devicePageQueryData.value.page = val
    getDevices()
}

// 是否在编辑设备，若为true则呼出右侧编辑窗口
const isEditing = ref(false)
// 当前设备，用于承载编辑设备与添加设备的表单
const currentDevice = ref({})

const updateDeviceInfo = async () => {
    // 调用接口
    let result = await deviceInfoUpdateService(currentDevice.value)
    ElMessage.success(result.msg ? result.msg : '修改成功')
}

// 图片上传成功的回调函数
const uploadSuccess = (result) => {
    currentDevice.value.image = result.data
}

// 查看设备详情
const isViewing = ref(false)
const viewDevice = async (row) => {
    isViewing.value = true
    currentDevice.value = row
}
// 编辑设备
const editDevice = async (row) => {
    let result = await deviceInfoGetService(row.id)
    currentDevice.value = result.data
    await getParentName(currentDevice.value.parentId)
    isEditing.value = true
}

// 删除设备使用ElMessageBox判断
const deleteDevice = (row) => {
    ElMessageBox.confirm(
        '要删除该设备吗?',
        'Warning',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(async () => {
        let id = row.id
        let result = await deviceDeleteService(id)
        ElMessage.success(result.msg ? result.msg : '删除成功')
        getDevices()
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '已取消',
        })
    })
}

// 取消编辑
const cancelClickEditing = () => {
    isEditing.value = false
}

// 提交编辑
const confirmClickEditing = async () => {
    await updateDeviceInfo()
    isEditing.value = false
    parentDeviceName.value = ''
    
    getDevices()
}

// 是否在添加新设备，若为true则呼出右侧新增设备窗口
const isAdding = ref(false)

const addDevice = async () => {
    // 调用接口
    let result = await deviceRegisterService(currentDevice.value)
    ElMessage.success(result.msg ? result.msg : '新增成功')
}

// 添加新设备，初始化currentDevice表单
const addDeviceButton = () => {
    currentDevice.value = {
        id: null,
        name: '',
        type: '',
        posId: '',
        parentId: '',
        districtId: '',
        macAddr: ''
    }
    isAdding.value = true
}

// 取消新增设备
const cancelClickAdding = () => {
    isAdding.value = false
    parentDeviceName.value = ''
}

// 提交新增设备
const confirmClickAdding = async () => {
    await addDevice()
    isAdding.value = false
    parentDeviceName.value = ''

    getDevices()
}
</script>

<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>设备管理</span>
            </div>
        </template>

        <div>
            <!-- 顶部栏，包含分页查询过滤条件，以及创建新设备 -->
            <el-form class="search-filter" :model="devicePageQueryData">
                <el-form-item label="设备编号">
                    <el-input v-model="devicePageQueryData.id" type="number"></el-input>
                </el-form-item>
                <el-form-item label="设备名称">
                    <el-input v-model="devicePageQueryData.name" type="text"></el-input>
                </el-form-item>
                <el-form-item label="所属片区">
                    <el-tree-select
                        v-model="devicePageQueryData.districtId"
                        :data="parsedDistrictTreeData"
                        check-strictly
                        clearable
                        :render-after-expand="false"
                        style="width: 240px"
                    />
                </el-form-item>
                <el-form-item label="设备状态" prop="status">
                    <el-select
                    v-model="devicePageQueryData.status"
                    clearable
                    placeholder="选择设备状态"
                    >
                        <el-option
                        v-for="item in deviceStatusList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="设备类型" prop="status">
                    <el-select
                    v-model="devicePageQueryData.type"
                    placeholder="选择设备类型"
                    clearable
                    size="large"
                    >
                        <el-option
                        v-for="item in deviceTypeList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="getDevices">搜索</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button @click="addDeviceButton">新增设备</el-button>
                </el-form-item>
            </el-form>
        </div>

        <hr style="background-color: #eee; height: 1px; border: none;" />

        <!-- 设备表格 -->
        <el-table :data="devices" style="width: 100%">
            <el-table-column prop="id" label="设备编号" width="180" sortable />
            <el-table-column prop="name" label="设备名称" sortable />
            <el-table-column prop="macAddr" label="设备MAC地址" width="200" sortable />
            <el-table-column prop="parentId" label="父设备编号" sortable />
            <el-table-column prop="typeName" label="设备类型" sortable />
            <el-table-column prop="districtName" label="所属区域"  />
            <el-table-column prop="statusName" label="状态"  />
            <el-table-column prop="operations" label="操作" fixed="right">
                <template #default="scope">
                    <el-button link type="primary" size="small" @click="viewDevice(scope.row)">详情</el-button>
                    <el-button link type="primary" size="small" @click="editDevice(scope.row)">编辑</el-button>
                    <el-button link type="danger" size="small" @click="deleteDevice(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 页码切换组件 -->
        <div class="pagination-block">
            <el-pagination
                layout="prev, pager, next, sizes"
                :total="itemsTotal"
                :page-size="devicePageQueryData.pageSize"
                v-model:current-page="devicePageQueryData.page"
                v-model:page-size="devicePageQueryData.pageSize"
                :page-sizes="[5, 10, 20, 50]"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />
        </div>
    </el-card>

    <!-- 查看设备详情的弹窗 -->
    <el-dialog v-model="isViewing" title="设备详情" width="80%" fullscreen destroy-on-close center>
        <DeviceDetail :deviceData="currentDevice" />
    </el-dialog>

    <!-- 编辑设备的侧边界面 -->
    <el-drawer v-model="isEditing" :direction="rtl" size="50%">
        <template #header>
            <h4>编辑 {{ currentDevice.id }} 信息</h4>
        </template>
        <template #default>
            <div class="form-edit-device">
                <el-row>
                    <el-col :span="18">
                        <el-form :model="currentDevice" :rules="rules" label-width="150px" size="large">
                            <el-form-item label="设备名称" prop="name">
                                <el-input v-model="currentDevice.name"></el-input>
                            </el-form-item>
                            <el-form-item label="设备MAC地址" prop="macAddr">
                                <el-input v-model="currentDevice.macAddr"></el-input>
                            </el-form-item>
                            <el-form-item label="设备类型" prop="type">
                                <el-select
                                v-model="currentDevice.type"
                                placeholder="选择设备类型"
                                size="large"
                                >
                                    <el-option
                                    v-for="item in deviceTypeList"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                    />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="父设备编号" prop="parentId" v-if="currentDevice.type === 'drinker'">
                                <el-input v-model="currentDevice.parentId" type="number" @input="getParentName(currentDevice.parentId)"><template #append>{{ parentDeviceName }}</template></el-input>
                            </el-form-item>
                            <el-form-item label="所属片区" prop="districtId">
                                <el-tree-select
                                    v-model="currentDevice.districtId"
                                    :data="parsedDistrictTreeData"
                                    clearable
                                    :render-after-expand="false"
                                    style="width: 240px"
                                />
                            </el-form-item>
                        </el-form>
                    </el-col>
                </el-row>
            </div>
        </template>
        <template #footer>
            <div style="flex: auto">
                <el-button @click="cancelClickEditing">取消</el-button>
                <el-button type="primary" @click="confirmClickEditing">确认</el-button>
            </div>
        </template>
    </el-drawer>

    <!-- 新增设备的侧边界面 -->
    <el-drawer v-model="isAdding" :direction="rtl" size="50%">
        <template #header>
            <h4>新增设备</h4>
        </template>
        <template #default>
            <div class="form-edit-device">
                <el-row>
                    <el-col :span="18">
                        <el-form :model="currentDevice" :rules="rules" label-width="150px" size="large">
                            <el-form-item label="设备名称" prop="name">
                                <el-input v-model="currentDevice.name"></el-input>
                            </el-form-item>
                            <el-form-item label="设备MAC地址" prop="macAddr">
                                <el-input v-model="currentDevice.macAddr"></el-input>
                            </el-form-item>
                            <el-form-item label="设备类型" prop="type">
                                <el-select
                                v-model="currentDevice.type"
                                placeholder="选择设备类型"
                                size="large"
                                >
                                    <el-option
                                    v-for="item in deviceTypeList"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                    />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="父设备编号" prop="parentId" v-if="currentDevice.type == 'drinker'">
                                <el-input v-model="currentDevice.parentId" type="number" @input="getParentName(currentDevice.parentId)"><template #append>{{ parentDeviceName }}</template></el-input>
                            </el-form-item>
                            <el-form-item label="所属片区" prop="districtId">
                                <el-tree-select
                                    v-model="currentDevice.districtId"
                                    :data="parsedDistrictTreeData"
                                    clearable
                                    :render-after-expand="false"
                                    style="width: 240px"
                                />
                            </el-form-item>
                        </el-form>
                    </el-col>
                </el-row>
            </div>
        </template>
        <template #footer>
            <div style="flex: auto">
                <el-button @click="cancelClickAdding">取消</el-button>
                <el-button type="primary" @click="confirmClickAdding">确认</el-button>
            </div>
        </template>
    </el-drawer>
</template>

<style scoped>
.search-filter {
    width: 100%;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    
}

.pagination-block {
    display: flex;
    align-items: center;
    justify-content: center;
}

.form-edit-device {
    display: flex;
    flex-direction: column;
    justify-content: center;
}
</style>
